<template>
<!-- 促销商品管理 -->
  <div class="page-box">
    <el-form :inline="true" :model="searchData" ref="form">
      <el-form-item label="供应商">
        <el-select v-model="searchData.sysOrgId" placeholder="请选择供应商" filterable clearable>
          <el-option
            v-for="emall in emalls"
            :key="emall.id"
            :label="emall.orgNameZhShort"
            :value="emall.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="sku">
        <el-input v-model="searchData.sku" placeholder="请输入sku" ></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchData.releaseStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="releaseStatus in status"
            :key="releaseStatus.value"
            :label="releaseStatus.label"
            :value="releaseStatus.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" icon="el-icon-search" @click="handleCurrentChange(1)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row class="page-box-tool">
      <el-button icon="el-icon-plus" type="success" @click="openDialogAdd()">新增</el-button>
    </el-row>

    <!-- 表格 -->
    <el-table
        border
        :data="tableData"
        :max-height="maxHeightNow"
        style="width: 100%"
        >
      <el-table-column prop="orgNameZh" label="供应商"  width="150" fixed></el-table-column>
      <el-table-column prop="goodsName" label="商品名称"  width="300" fixed></el-table-column>
      <el-table-column prop="sku" label="商品sku"  width="120" ></el-table-column>
      <el-table-column prop="upDownStatus" label="商品状态"  width="100"></el-table-column>
      <el-table-column prop="price" label="促销价格"  width="90"></el-table-column>
      <el-table-column prop="num" label="促销数量"  width="90"></el-table-column>
      <el-table-column prop="beginTime" label="促销开始时间"  width="180"></el-table-column>
      <el-table-column prop="endTime" label="促销结束时间"  width="180"></el-table-column>
      <el-table-column prop="strReleaseStatus" label="状态"  width="100">
        <template slot-scope="scope">
          {{statusArr[scope.row.releaseStatus]}}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="申请时间"  width="180">
        <template slot-scope="scope">
          {{scope.row.createTime.replace("T"," ")}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.releaseStatus != '0'" type="primary" size="mini" @click="openDialogEdit(scope.row)">
            编辑
          </el-button>
          <el-button :disabled="scope.row.releaseStatus != '0'" type="danger" size="mini" @click="deleteData(scope.row)">
            删除
          </el-button>
          <el-button :disabled="scope.row.releaseStatus != '0'" type="warning" size="mini" @click="discountRelease(scope.row)">发布</el-button>
          <!-- <el-button type="warning" size="mini" @click="endDiscount(scope.row)">取消发布</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size=pageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total=totalPage>
    </el-pagination>

    <!--  新增/编辑-->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="45%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <el-form ref="discountForm" :model="discountForm" label-width="110px" :rules="rules">
        <el-form-item label="供应商" prop="sysOrgId">
          <el-select v-model="discountForm.sysOrgId" placeholder="请选择供应商" filterable clearable @change="checkItem()">
            <el-option
            v-for="emall in emalls"
            :key="emall.id"
            :label="emall.orgNameZhShort"
            :value="emall.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="促销sku" prop="sku">
          <el-input v-model="discountForm.sku" placeholder="请输入sku" @blur="checkItem()"></el-input>
        </el-form-item>
        <el-form-item label="促销商品" >
          <p v-bind:class="{'text-danger': tmpItem.haveNotItem }" >{{tmpItem.name}}</p>
        </el-form-item>
        <el-form-item label="促销价格" prop="price">
          <el-input-number v-model="discountForm.price" :precision="2" :step="1" :max="9000000" :min="0" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="促销数量" prop="num">
          <el-input-number v-model="discountForm.num" :precision="0" :step="1" :max="9000000" :min="1" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="促销时间范围" prop="discountTime">
          <el-date-picker v-model="discountForm.discountTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="dialogSubmit()">确 定</el-button>
    </span>
    </el-dialog>

  </div>
</template>

<script>
  import { getAllSuppliers, getGoodsItemBysku, getPromotionPrice, setPromotionPrice, modifyPromotionPrice,
    delPromotionPrice, discountPriceRelease,endDiscount} from '@/api/admin.api';
  import VueLazyload from 'vue-lazyload'
  export default {
    name: 'discount-manager',
    components: {},
    data() {
      return {
        searchData:{},
        emalls:[], //电商列表
        status:[    //状态列表
          {
            value:"0",
            label:"新建"
          },
          {
            value:"1",
            label:"生效"
          },
          {
            value:"2",
            label:"完成"
          },
        ],
        statusArr:["新建","生效","完成"],
        tableData:[],

        currentPage:1,
        pageSize:10,
        totalPage:0,

        dialogTitle: '',
        dialogVisible: false,
        isEdit:false,


        discountForm:{},
        rules:{
          sysOrgId:[{ required: true, message: '请选择供应商', trigger: 'change' }],
          sku:[{ required: true, message: '请输入sku', trigger: 'blur' }],
          price:[{ required: true, message: '请输入促销价格', trigger: 'blur' }],
          num:[{ required: true, message: '请输入促销数量', trigger: 'blur' }],
          discountTime:[{ required: true, message: '请选择促销时间', trigger: 'change' }],
        },
        tmpItem:{
          sku:"",
          name:"",
          goodsId:"",
          haveNotItem:true
        }


      }
    },
    watch: {},
    computed: {
      maxHeightNow () {
        const height = window.innerHeight
        return height -  320
      }
    },
    created() {
      this.getEmallList();
      this.onSearch();
    },
    mounted() {
    },
    methods: {
      getEmallList(){
        getAllSuppliers().then( res =>{
          this.emalls = res
        })
      },
      onSearch(){
        const params = {
          size: this.pageSize,
          current: this.currentPage,
          sysOrgId: this.searchData.sysOrgId,
          sku: this.searchData.sku,
          releaseStatus: this.searchData.releaseStatus
        }
        getPromotionPrice(params).then( res =>{
          this.tableData = res.records
          this.totalPage = res.total
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
        this.onSearch()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.onSearch()
      },

      openDialogAdd(){
        this.dialogVisible = true;
        this.dialogTitle= "添加";
        if(this.$refs["discountForm"] !=undefined){
          this.$refs["discountForm"].resetFields();
        }
        this.discountForm={};
        this.tmpItem={
          sysOrgId:"",
          sku:"",
          name:"",
          goodsId:"",
          haveNotItem:true
        };
        this.isEdit=false;

      },
      openDialogEdit(row){
        this.dialogVisible = true;
        this.dialogTitle= "修改";
        if(this.$refs["discountForm"] !=undefined){
          this.$refs["discountForm"].resetFields();
        }
        this.discountForm={
          id:row.id,
          num:row.num,
          price:row.price,
          sku:row.sku,
          sysOrgId:row.sysOrgId,
          discountTime:[row.beginTime,row.endTime],
          beginTime:row.beginTime,
          endTime:row.endTime,
          goodsId:row.goodsId
        };
        this.isEdit=true;
        this.tmpItem={
          sysOrgId:row.sysOrgId,
          sku:row.sku,
          name:row.goodsName,
          goodsId:row.goodsId,
          haveNotItem:false
        };

      },

      checkItem(){
        if(!this.discountForm.sku || !this.discountForm.sysOrgId){
          this.tmpItem={
            sysOrgId:"",
            sku:"",
            name:"",
            goodsId:"",
            haveNotItem:true
          }
          return;
        }
        if(this.discountForm.sku==this.tmpItem.sku && this.discountForm.sysOrgId==this.tmpItem.sysOrgId){
          return;
        }

        this.tmpItem.sysOrgId = this.discountForm.sysOrgId;
        this.tmpItem.sku = this.discountForm.sku;
        this.tmpItem.name='';
        this.tmpItem.goodsId='';

        getGoodsItemBysku(this.tmpItem.sysOrgId, this.tmpItem.sku).then(res => {
          this.tmpItem.name=res.goodsName;
          this.tmpItem.goodsId=res.id;
          this.tmpItem.haveNotItem=false;
        }).catch (err => {
          this.tmpItem.name='未查找到该sku所对应的商品，请您检查该sku的正确性';
          this.tmpItem.haveNotItem=true;
        })

      },

      dialogSubmit(){
        this.$refs["discountForm"].validate((valid) => {
          if (valid) {
            if(this.tmpItem.haveNotItem){
              this.$message.error('您填写的商品sku有误');
              return
            }

            this.discountForm.beginTime=this.discountForm.discountTime[0];
            this.discountForm.endTime=this.discountForm.discountTime[1];
            this.discountForm.goodsName=this.tmpItem.name;
            this.discountForm.goodsId=this.tmpItem.goodsId;

            if(this.discountForm.beginTime>=this.discountForm.endTime){
              this.$message.error('促销结束时间不可小于等于开始时间');
              return
            }

            if(this.isEdit){
              modifyPromotionPrice(this.discountForm).then(res => {
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                });
                // 查询角色列表
                this.onSearch ()
                this.dialogVisible = false
              })
            }else{
              setPromotionPrice(this.discountForm).then(res => {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                // 查询角色列表
                this.onSearch ()
                this.dialogVisible = false
              })
            }

          }
        })

      },

      discountRelease(row){
        this.$confirm('是否确定发布此条促销信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          discountPriceRelease(row.id).then(res => {
            this.$message({
              type: 'success',
              message: '发布成功!'
            });
            this.onSearch ()
          })

        });

      },
	endDiscount(row){
        this.$confirm('是否取消发布此条促销信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          endDiscount(row.id).then(res => {
            this.$message({
              type: 'success',
              message: '取消发布成功!'
            });
            this.onSearch ()
          })

        });

      },
      deleteData(row){
        this.$confirm('是否确定删除此条促销信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delPromotionPrice(row.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.onSearch ()
          })

        });
      },
    }
  }
</script>

<style scoped lang="scss">
  .page-box {
    padding: 20px;
    background: white;
    .form-operation {
      text-align: right;
      .el-form-item {
        margin-right: 0;
      }
    }
    .el-pagination {
      padding: 20px;
      text-align: right;
    }
    &-tool {
      // text-align: right;
      padding-bottom: 20px;
    }
  }
  .text-danger{
    color: red;
  }
</style>
